<template>
    <div class="flex flex-col h-full w-full min-w-0">
        <div id="content-header">
            {{ currentResource?.name || '' }}
            <span v-if="hasUnsavedChange()" class="text-red-500 ml-1 font-bold">*</span>

            <div v-if="currentResource?.type === 'ItemStrings'">
                <span class="ml-2 text-sm text-gray-400">
                    JSON类型资源：ItemStrings（物品文本）
                </span>
                <br />
                <span class="text-sm text-gray-400">
                    修改方案：
                </span>
                <span>{{ currentResource?.files?.custom?.path }}</span>
                <br />

                <div id='fileCtrlBar' class="flex gap-2">
                    <button @click="handleLoadFile"
                        class="px-3 py-1 border border-gray-500 rounded hover:bg-purple-700 hover:border-purple-500 transition-colors">
                        导入
                    </button>
                    <button @click="saveCustom"
                        class="px-3 py-1 border border-gray-500 rounded hover:bg-blue-700 hover:border-blue-500 transition-colors">
                        保存
                    </button>
                    <button @click="handleSaveAsFile"
                        class="px-3 py-1 border border-gray-500 rounded hover:bg-green-700 hover:border-green-500 transition-colors">
                        另存为
                    </button>
                    <button @click="handleApplyCustomFileToMod"
                        class="px-3 py-1 border border-gray-500 rounded hover:bg-orange-700 hover:border-orange-500 transition-colors">
                        应用修改
                    </button>
                    <button @click="handelRestoreMod"
                        class="px-3 py-1 border border-gray-500 rounded hover:bg-red-700 hover:border-red-500 transition-colors">
                        恢复原始
                    </button>
                </div>
                <div id="showCols">
                    <span class="ml-2 text-sm text-gray-400">
                        表格显示列：
                    </span>
                    <!-- 列显示选择的checkboxes -->
                    <label v-for="col in Object.keys(tableColumns)" :key="col" class="ml-2 inline-flex items-center">
                        <input type="checkbox" :checked="tableColumns[col]"
                            @change="(event) => { const target = event.target as HTMLInputElement; onTableColsChange(col, target.checked); }"
                            class="form-checkbox h-4 w-4 text-blue-600" :id="`column-checkbox-${col}`" />
                        <span class="ml-1 text-xs text-gray-300">{{ col }}</span>
                    </label>
                </div>
                <div id="search">
                    <span class="ml-2 text-sm text-gray-400">
                        输入关键字：
                    </span>
                    <input type="text" v-model="searchKeyword" placeholder="输入关键字"
                        class="ml-2 p-1 border border-gray-300 rounded outline-none" @keyup.enter="handleSearch" />
                    <!-- 新增：搜索按钮 -->
                    <button @click="handleSearch"
                        class="ml-2 px-2 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">
                        搜索
                    </button>

                </div>
            </div>
        </div>
        <!-- 第二行：属性面板控制按钮和类别筛选 -->
        <div v-if="currentResource?.type === 'ItemStrings'" class="bg-gray-800 p-2 border-b border-gray-300">
            <div class="flex justify-between items-center">
                <div class="flex items-center">


                    <div id="item-names-categorys" v-if="props.resourceItem?.name === 'item-names.json'">
                        <!-- 添加显示/隐藏切换按钮 -->
                        <div class="flex flex-start items-center">
                            <h3 class="text-sm font-medium text-white mr-2">类别筛选</h3>
                            <button @click="toggleOptionsVisible"
                                class="px-2 py-1 text-xs bg-black border border-gray-300 hover:bg-blue-400 rounded transition-colors">
                                {{ optionsVisible ? '隐藏' : '显示' }}
                            </button>
                        </div>
                        
                        <div id="option-list" class="p-3 bg-gray-700/50 rounded-md" v-if="optionsVisible">
                            <!-- 屏蔽状态筛选 -->
                            <div id="filter-state" class="mb-2">
                                <div class="text-sm text-gray-300 mb-1">屏蔽状态：</div>
                                <div class="flex flex-wrap gap-2">
                                    <label class="inline-flex items-center cursor-pointer px-2 py-1 rounded hover:bg-blue-400 transition-colors">
                                        <input type="radio" name="filterState" value="all" v-model="selectedFilterStateOption"
                                            @change="handleSearch"
                                            class="mr-1.5 h-3 w-3 text-blue-600 focus:ring-blue-300 border-gray-300 rounded-full">
                                        <span class="text-sm text-gray-300">所有</span>
                                    </label>
                                    <label class="inline-flex items-center cursor-pointer px-2 py-1 rounded hover:bg-blue-400 transition-colors">
                                        <input type="radio" name="filterState" value="blocked" v-model="selectedFilterStateOption"
                                            @change="handleSearch"
                                            class="mr-1.5 h-3 w-3 text-blue-600 focus:ring-blue-300 border-gray-300 rounded-full">
                                        <span class="text-sm text-gray-300">已屏蔽</span>
                                    </label>
                                    <label class="inline-flex items-center cursor-pointer px-2 py-1 rounded hover:bg-blue-400 transition-colors">
                                        <input type="radio" name="filterState" value="unblocked" v-model="selectedFilterStateOption"
                                            @change="handleSearch"
                                            class="mr-1.5 h-3 w-3 text-blue-600 focus:ring-blue-300 border-gray-300 rounded-full">
                                        <span class="text-sm text-gray-300">未屏蔽</span>
                                    </label>
                                </div>
                                <div class="h-px bg-gray-400 mt-2"></div>
                            </div>
                            
                            <!-- 级别筛选 -->
                            <div id="level" class="mb-2">
                                <div class="text-sm text-gray-300 mb-1">级别：</div>
                                <div class="flex flex-wrap gap-2">
                                    <label v-for="level in levelOptions" :key="level.key"
                                        class="inline-flex items-center cursor-pointer px-2 py-1 rounded hover:bg-blue-400 transition-colors">
                                        <input type="radio" :name="'level-group'" :value="level.key"
                                            v-model="selectedLevelOption"
                                            class="mr-1.5 h-3 w-3 text-blue-600 focus:ring-blue-300 border-gray-300 rounded-full"
                                            @change="handleSearch">
                                        <span class="text-sm text-gray-300">{{ level.label }}</span>
                                    </label>
                                </div>
                                <div class="h-px bg-gray-400 mt-2"></div>
                            </div>
                            
                            <!-- 类型筛选 -->
                            <div id="sub-category">
                                <div class="text-sm text-gray-300 mb-1">类型：</div>
                                <div class="flex flex-wrap gap-2">
                                    <label v-for="subCategory in subCategoryOptions" :key="subCategory.key"
                                        class="inline-flex items-center cursor-pointer px-2 py-1 rounded hover:bg-blue-400 transition-colors">
                                        <input type="radio" :name="'sub-category-group'" :value="subCategory.key"
                                            v-model="selectedSubCategoryOption"
                                            class="mr-1.5 h-3 w-3 text-blue-600 focus:ring-blue-300 border-gray-300 rounded-full"
                                            @change="handleSearch">
                                        <span class="text-sm text-gray-300">{{ subCategory.label }}</span>
                                    </label>
                                </div>
                                <div class="h-px bg-gray-400 mt-2"></div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        </div>
        <div class="py-2 flex justify-end">
            <button v-if="currentResource?.type === 'ItemStrings'" @click="togglePropPanel"
                class="px-3 py-1 bg-gray-700 text-white rounded text-sm hover:bg-gray-600 mr-4">
                {{ showPropPanel ? '隐藏属性面板' : '显示属性面板' }}
            </button>
        </div>
        <div class="center-body flex-1 overflow-hidden flex">
            <!-- 左侧内容区域 -->
            <div class="flex-1 overflow-hidden border-r border-gray-300">
                <div class="table-placeholder" v-if="!currentResource">
                    <p>请选左侧具体Mod的资源项查看内容</p>
                </div>
                <!-- 渲染选中的资源内容 -->
                <div v-else class="content-container flex flex-col h-full">
                    <div class="content-data-wrapper flex-1 overflow-hidden">
                        <!-- JSON类型资源的显示 -->
                        <div class="content-data h-full overflow-auto bg-black">
                            <div class="w-full h-full overflow-auto p-4">
                                <table class="w-full border-collapse">
                                    <thead>
                                        <tr>
                                            <th class="border border-gray-300 px-4 py-2 bg-transparent text-center">地面显示
                                            </th>
                                            <th class="border border-gray-300 px-4 py-2 bg-transparent text-center">Key
                                            </th>
                                            <th v-if="tableColumns.zhCN"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                中文（简体）</th>
                                            <th v-if="tableColumns.zhTW"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                中文（繁体）</th>
                                            <th v-if="tableColumns.enUS"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                英文（美国）</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="item in displayItems" :key="item.id" @click="selectedItem = item"
                                            :class="{ 'bg-blue-900/30': selectedItem?.id === item.id }">
                                            <td class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                <input type="checkbox" :checked="item.isShow"
                                                    @change="handleIsShowChange(item.Key)" class="mx-auto" />
                                            </td>
                                            <td class="border border-gray-300 px-4 py-2 bg-transparent text-center">{{
                                                item.Key }}</td>
                                            <!-- 中文（简体） -->
                                            <td v-if="tableColumns.zhCN"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                <D2TextBox :text="item.zhCN" :key-prefix="`zhcn-${item.id}`" />
                                            </td>
                                            <!-- 中文（繁体） -->
                                            <td v-if="tableColumns.zhTW"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                <D2TextBox :text="item.zhTW" :key-prefix="`zhtw-${item.id}`" />
                                            </td>
                                            <!-- 英文（美国） -->
                                            <td v-if="tableColumns.enUS"
                                                class="border border-gray-300 px-4 py-2 bg-transparent text-center">
                                                <D2TextBox :text="item.enUS" :key-prefix="`enus-${item.id}`" />
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧属性面板，仅在显示ItemStrings表格且有选中项且showPropPanel为true时显示 -->
            <div v-if="showPropPanel && currentResource?.type === 'ItemStrings' && selectedItem"
                class="w-80 overflow-auto">
                <ItemPropPanel :item="selectedItem" :resourceItemName="props.resourceItem?.name"
                    @searchSpecLevelItem="handleSearchSpecLevelItem" @saveItemEdit="handlePropPanelSaveItem" />
            </div>
        </div>
    </div>
</template>


<script setup lang="ts">
// 修改script setup部分，添加搜索相关的响应式数据和方法，以及选中项状态管理
import { ref, watch, onMounted } from 'vue';
import { D2ItemStringToDisplay, ResourceItem, D2ItemDesc, AppTauriConfig, UserModifiedData } from './types';
import { ResFileInfo } from './resFileInfo';
import { D2ItemString } from '../common/d2Types';
import D2TextBox from './D2TextBox.vue';
import ItemPropPanel from './ItemPropPanel.vue'; // 导入ItemPropPanel组件
import appContext from '../common/appContext.json'; //这是程序上下文，包含了颜色表，和有效物品Key
import itemDescs from '../common/item-descs.json';
//创作者模式(未实现)，会显示所有物品，包括非底材的暗金，套装文字，显示符文之语等等
const enableCreatorMode = ref<boolean>(false);

const props = defineProps<{ resourceItem?: ResourceItem; tauriConfig?: AppTauriConfig; }>();
// 内部响应式数据
const currentResource = ref<ResourceItem | undefined>(undefined);
const hasItemPropChange = ref<boolean>(false);
const hasItemIgnoreChange = ref<boolean>(false);

/**用户在游戏内使用的语言*/
const userLang = ref<string>('zhCN');
// 控制右侧属性面板显示/隐藏
const showPropPanel = ref<boolean>(true);

//所有物品项,载入后就不会变化，可用于重置用户修改
const allItems = ref<D2ItemStringToDisplay[]>([]);
//用户修改的物品项，会在保存时和allItems合并后写入文件
const editItems = ref<D2ItemStringToDisplay[]>([]);


//显示物品项，会根据搜索，选择分类所变化
const displayItems = ref<D2ItemStringToDisplay[]>([]);
//选中物品项，会在右边面板显示物品属性
const selectedItem = ref<D2ItemStringToDisplay | undefined>(undefined); // 选中的物品项
//物品分类的装备级别，
const levelOptions = ref<Array<{ key: number | undefined, label: string }>>([
    { key: -1, label: "所有" },
    { key: 1, label: "普通" },
    { key: 2, label: "扩展" },
    { key: 3, label: "精华" },
    { key: 0, label: "其他" },
]);
//分类的装备类型，这个类型应该(?)和符文之语相关
const subCategoryOptions = ref<Array<{ key: string | undefined, label: string }>>([]);
const selectedLevelOption = ref<number>(-1);
const selectedSubCategoryOption = ref<string | undefined>('all');
// 列显示状态表
const tableColumns = ref<{ [key: string]: boolean }>({
    zhCN: true,
    zhTW: true,
    enUS: true
});
//从user文件加载的修改数据
const loadedUserDataModifiedItems = ref<UserModifiedData | undefined>(undefined);
//在工作空间手动编辑的修改数据
const workSpaceModifiedItems = ref<UserModifiedData | undefined>(undefined);



onMounted(() => {
    //初始化时候，载入物品分类的装备类型
    const subCategLabelMap: { [key: string]: string } = appContext.equipSubCategoryLabels;
    for (const key in subCategLabelMap) {
        subCategoryOptions.value.push({ key: key, label: subCategLabelMap[key] });
    }
    //在头部插入"所有"
    subCategoryOptions.value.unshift({ key: 'all', label: "所有" });
});

// 每当主页上，确认载入最左边的资源时，这个props变量就会发生变化，触发这个watch
watch(() => props.resourceItem, async (newResource) => {
    if (newResource) {
        // 重置选中项
        selectedItem.value = undefined;
        // 创建副本以避免直接修改prop
        currentResource.value = { ...newResource };
        if (newResource.type === 'ItemStrings' && newResource.name && newResource.files) {
            // 加载物品字符串
            const templateFile = newResource.files.template;
            if (templateFile) {
                await templateFile.read();
                loadCompleteItemStrings(newResource.name, templateFile.content || '');
                //默认没有用户修改数据，初始化一份

                workSpaceModifiedItems.value = {
                    modName: currentResource.value?.modName || '',
                    ignoreItemKeys: [],
                    modifiedItemStrings: {}
                };

                const customFile = newResource.files.custom;
                if (!customFile || (customFile.path && !await customFile.exists())) {
                    const newCustomFile = new ResFileInfo();
                    newCustomFile.filename =  '';
                    newCustomFile.path = '';
                    newResource.files.custom = newCustomFile;
                } 
            } else {
                console.log(`物品字符串资源 ${newResource.name} 没有模板文件`);
                alert(`物品表 ${newResource.name} 没有模板文件 data/template/${newResource.modName}/${newResource.name}，无法加载`);
                return;
            }
            hasItemPropChange.value = false;
            hasItemIgnoreChange.value = false;
        }
    }
}, { immediate: true });

function hasUnsavedChange(): boolean {
    return hasItemPropChange.value || hasItemIgnoreChange.value;
}

// 处理列（zhCN,zhTW,enUS）显示状态变化的方法
const onTableColsChange = (column: string, checked: boolean) => {
    // 更新列显示状态
    tableColumns.value[column] = checked;
};

// 新增：搜索关键字
const searchKeyword = ref<string>('');
// 新增：屏蔽状态筛选选项
const selectedFilterStateOption = ref<string>('all');
// 新增：搜索功能实现
// 控制选项列表显示/隐藏的状态
const optionsVisible = ref<boolean>(true);

// 切换选项列表显示状态
const toggleOptionsVisible = () => {
    optionsVisible.value = !optionsVisible.value;
};

//搜索方法
const handleSearch = () => {

    displayItems.value = [...editItems.value];

    // 新增：屏蔽状态筛选
    if (selectedFilterStateOption.value === 'blocked') {
        // 筛选已屏蔽的物品
        displayItems.value = displayItems.value.filter(item => !item.isShow);
    } else if (selectedFilterStateOption.value === 'unblocked') {
        // 筛选未屏蔽的物品
        displayItems.value = displayItems.value.filter(item => item.isShow);
    }
    //首先进行物品分类
    //1级别分类
    if (selectedLevelOption.value !== -1) {
        if (selectedLevelOption.value !== 0) {
            displayItems.value = editItems.value.filter(item => {
                if (item.desc === undefined || item.desc.level === undefined) {
                    return false;
                }
                return item.desc.level === selectedLevelOption.value;
            });
        } else {
            displayItems.value = editItems.value.filter(item => {
                if (item.desc === undefined || item.desc.level === undefined) {
                    return true;
                } else {
                    return ![1, 2, 3].includes(item.desc.level);
                }
            });
        }

    }
    //2装备类型分类
    if (selectedSubCategoryOption.value !== undefined && selectedSubCategoryOption.value !== 'all') {
        displayItems.value = displayItems.value.filter(item => {
            if (item.desc === undefined || item.desc.subCateg === undefined) {
                return false;
            }
            return item.desc.subCateg === selectedSubCategoryOption.value;
        });
    }


    // 如果搜索关键字为空，则显示所有项目
    if (!searchKeyword.value.trim()) {
        return;
    }
    const keyword = searchKeyword.value.toLowerCase().trim();
    // 过滤项目：保留任意已经勾选显示的一列中包含关键字的条目，或Key字段包含关键字
    displayItems.value = displayItems.value.filter(item => {
        // 1. 检查item.Key字段是否包含关键字（无论是否显示在表格中）
        if (item.Key && typeof item.Key === 'string' && item.Key.toLowerCase().includes(keyword)) {
            return true;
        }
        // 2. 检查所有显示的列是否包含关键字
        return Object.keys(tableColumns.value).some(column => {
            // 只检查当前显示的列
            if (tableColumns.value[column]) {
                // 获取该列的值
                const value = item[column as keyof D2ItemStringToDisplay];
                // 如果值是字符串，则检查是否包含关键字
                if (typeof value === 'string') {
                    return value.toLowerCase().includes(keyword);
                }
            }
            return false;
        });
    });
};



import JSON5 from 'json5';
import { exists, readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';
import { open, save } from '@tauri-apps/plugin-dialog';
import { resourceDir } from '@tauri-apps/api/path';

//给与json文本，载入物品字符串，并且筛选用户关注的几个语言用于显示
function loadCompleteItemStrings(name: string, templateCotent: string): boolean {
    if (templateCotent === undefined || templateCotent === '') {
        return false;
    }
    try {
        console.log("loadCompleteItemStrings", "载入文件名称", name);
        allItems.value = [];
        editItems.value = [];
        const items = JSON5.parse(templateCotent) as D2ItemString[];

        const validKeys: Array<string> = [];
        if (name === 'item-names.json') {
            //所有地面能显示的物品都在这个有效健里面，其他文本对一般用户无意义
            validKeys.push(...appContext.equipKeys.concat(appContext.miscKeys));
        } else if (name === 'item-runes.json') {
            //按照符文的key规律来筛选有效健
            const allKeysInFile = items.map(i => i.Key);
            const runeOnlyKeys = [];
            for (const k in allKeysInFile) {
                if (/^r\d+$/.test(allKeysInFile[k])) {
                    runeOnlyKeys.push(allKeysInFile[k]);
                }
            }
            //validKeys.push(...appContext.runeKeys);
            //测试，获取所有key
            validKeys.push(...runeOnlyKeys);
        }

        //1.载入模板中的物品项目，这是不更改的
        for (const item of items) {
            const displayItem: D2ItemStringToDisplay = {
                isShow: checkItemIsShowByLang(item),
                id: item.id,
                Key: item.Key,
                zhCN: item.zhCN,
                zhTW: item.zhTW,
                enUS: item.enUS,
                desc: undefined
            }
            allItems.value.push(displayItem);
            // 如果物品的Key不在有效键中，跳过
            if (!validKeys.includes(item.Key) && !enableCreatorMode.value) {
                continue;
            }
            let desc = (itemDescs as Array<D2ItemDesc>).find(d => d.Key === item.Key);
            if (desc === undefined) {
                if (name === 'item-runes.json') {
                    if (appContext.miscKeys.includes(item.Key)) {
                        desc = {
                            Key: item.Key,
                            level: 0,
                            subCateg: 'other',
                            name: item.zhCN,
                            details: [],
                            imageName: item.Key,
                            mainCateg: 'misc',
                        }
                    }
                } else {
                    //console.log("loadCompleteItemStrings", "物品描述未找到", item.zhCN, item.Key);
                }
            }
            //这里从item-descs.json载入数据
            displayItem.desc = desc || undefined;
            // 使用JSON序列化和反序列化实现深拷贝
            const clonedItem = JSON.parse(JSON.stringify(displayItem));
            editItems.value.push(clonedItem);
        }

        displayItems.value = [...editItems.value];
    } catch (e) {
        console.log("loadCompleteItemStrings", "载入物品字符串失败", e);
        return false;
    }

    return true;
}



async function tryLoadCustomFile(resFile: ResFileInfo): Promise<boolean> {
    try {
        if (!await resFile.exists()) {
            console.log("tryLoadCustomFile", "记录修改的文件不存在", resFile.path);
            return false;
        }
        await resFile.read();
        const customData = JSON5.parse(resFile.content || "") as UserModifiedData;
        if (customData === undefined) {
            console.log("tryLoadCustomFile", "记录修改的文件内容为空");
            return false;
        }
        if (customData.modName !== currentResource.value?.modName) {
            console.log("tryLoadCustomFile", "记录修改的文件MOD名与当前资源文件不匹配");
            return false;
        }
        //先将地面忽略的物品的勾选置为false
        if (customData.ignoreItemKeys && customData.ignoreItemKeys.length > 0) {
            for (const k of customData.ignoreItemKeys) {
                for (const item of editItems.value) {
                    if (item.Key === k) {
                        item.isShow = false;
                        break;
                    }
                }
            }
        }
        if (customData.modifiedItemStrings && Object.keys(customData.modifiedItemStrings).length > 0) {
            for (const k of Object.keys(customData.modifiedItemStrings)) {
                for (const item of editItems.value) {
                    if (item.Key === k) {
                        const itemOfUserData = customData.modifiedItemStrings[k];
                        item.zhCN = itemOfUserData.zhCN || item.zhCN;
                        item.zhTW = itemOfUserData.zhTW || item.zhTW;
                        item.enUS = itemOfUserData.enUS || item.enUS;
                    }
                }
            }
        }
        //属于从文件加载的修改，用户不会直接修改
        loadedUserDataModifiedItems.value = customData;
        //给软件工作空间初始化一份一样的深拷贝，用户在工作空间的修改会同步到这份数据
        workSpaceModifiedItems.value = JSON.parse(JSON.stringify(customData));

       
        //写入config文件
        await trySaveCustomFileToConfig(resFile.path);

        if (!currentResource.value.files) {
            currentResource.value.files = {};
        }
        currentResource.value.files.custom = resFile;
        console.log("tryLoadCustomFile", `成功加载记录修改的文件${resFile.filename}`, `屏蔽条目数${customData.ignoreItemKeys?.length || 0}`, `修改条目数${Object.keys(customData.modifiedItemStrings || {}).length}`);
        //重置修改状态
        hasItemPropChange.value = false;
        hasItemIgnoreChange.value = false;
        return true;
    } catch (e) {
        console.log("tryLoadCustomFile", "读取用户数据文件失败", e);
        return false;
    }
}

async function trySaveCustomFileToConfig(customPath: string | undefined) {
    var configObj = props.tauriConfig;
    if (!configObj) {
        console.log("trySaveCustomFileToConfig", "配置文件为空");
        return;
    }
    if (undefined === configObj.customFiles) {
        configObj.customFiles = {};
    }
    //当前mod的 资源文件-用户定制文件 映射表
    const modName = currentResource.value?.modName;
    if (undefined === modName) {
        console.log("trySaveCustomFileToConfig", "没有提供有效的MOD名");
        return;
    }
    const currentModCustomFiles = configObj.customFiles[modName];
    if (undefined === currentModCustomFiles) {
        configObj.customFiles[modName] = {};
    }
    const filename = currentResource.value?.name;
    if (undefined === filename) {
        console.log("trySaveCustomFileToConfig", "没有获取到当前资源的文件名");
        return;
    }
    if (currentModCustomFiles[filename] !== customPath) {
        currentModCustomFiles[filename] = customPath || '';
        writeTextFile('data/config.json', JSON.stringify(configObj, null, 2));
        console.log("trySaveCustomFileToConfig", `写入${customPath}到config.json，为mod ${currentResource.value?.modName} 的 ${filename}文件的修改内容`);
        return;
    }
    console.log("trySaveCustomFileToConfig", `配置表中的${currentResource.value?.modName} MOD文件中的 ${filename} 对应修改文件没有变化,跳过写入`);
    return;


}

function handleIsShowChange(itemKey: string) {
    const item = editItems.value.find(i => i.Key === itemKey);
    if (item) {
        // 切换显示状态
        item.isShow = !item.isShow;

        // 确保workSpaceModifiedItems存在并初始化ignoreItemKeys数组
        if (!workSpaceModifiedItems.value) {
            return;
        }
        if (!workSpaceModifiedItems.value.ignoreItemKeys) {
            workSpaceModifiedItems.value.ignoreItemKeys = [];
        }

        // 根据item.isShow状态更新ignoreItemKeys数组
        const ignoreItemKeys = workSpaceModifiedItems.value.ignoreItemKeys;
        const index = ignoreItemKeys.indexOf(itemKey);

        if (!item.isShow && index === -1) {
            // 如果不显示且不在忽略列表中，添加到忽略列表
            ignoreItemKeys.push(itemKey);
        } else if (item.isShow && index !== -1) {
            // 如果显示且在忽略列表中，从忽略列表移除
            ignoreItemKeys.splice(index, 1);
        }

        // 比较workSpaceModifiedItems和loadedUserDataModifiedItems的ignoreItemKeys集合
        const workspaceKeys = workSpaceModifiedItems.value.ignoreItemKeys || [];
        const loadedKeys = loadedUserDataModifiedItems.value?.ignoreItemKeys || [];

        // 检查两个集合是否不同
        const areSetsDifferent =
            workspaceKeys.length !== loadedKeys.length ||
            workspaceKeys.some(key => !loadedKeys.includes(key)) ||
            loadedKeys.some(key => !workspaceKeys.includes(key));

        hasItemIgnoreChange.value = areSetsDifferent;
    }
}

async function saveCustom() {
    if (!hasUnsavedChange()) {
        console.log("saveCustom", "没有未保存的更改");
        alert("没有未保存的更改");
        return;
    }
    // 检查当前是否有指定的用户数据文件，没有就另存为
    const existFileInfo = currentResource.value?.files?.custom;
    if (undefined === existFileInfo || !await existFileInfo.exists()) {
        console.log("saveCustom", "当前没有指定的记录修改的文件，将转为另存为");
        await handleSaveAsFile();
        return;
    } else {
        await saveCustomAs(existFileInfo.path || '');
    }
}

//name是中文描述的方案文件
async function saveCustomAs(fullFilePath: string): Promise<boolean> {
    try {
        if (!workSpaceModifiedItems.value) {
            return false;
        }
        workSpaceModifiedItems.value.modName = currentResource.value?.modName || '';
        // 写入文件
        await writeTextFile(fullFilePath, JSON.stringify(workSpaceModifiedItems.value, null, 2));
        console.log("saveUserDataAs", `成功保存用户数据文件${fullFilePath}`);
        await trySaveCustomFileToConfig(fullFilePath);
        const existCustom = currentResource.value?.files?.custom;
        if (!existCustom) {
            if (currentResource.value && currentResource.value.files) {
                const fileinfo = new ResFileInfo();
                fileinfo.filename = fullFilePath.split(/[/\\]/).pop() || '';
                fileinfo.path = fullFilePath;
                currentResource.value.files.custom = fileinfo;
            }
        } else {
            existCustom.filename = fullFilePath.split(/[/\\]/).pop() || '';
            existCustom.path = fullFilePath;
        }

        //重置修改状态
        hasItemPropChange.value = false;
        hasItemIgnoreChange.value = false;
        return true;
    } catch (e) {
        return false;
    }
}



async function handleLoadFile() {
    if (hasUnsavedChange()) {
        if (!await confirm("当前有未保存的更改，是否继续加载？")) {
            return;
        }
    }

    try {
        // 获取可执行文件根目录的绝对路径
        const resdir = await resourceDir();
        console.log("resourceDir", resdir);
        // 构建完整的默认路径
        const defaultDirPath = `${resdir}/data/custom`;

        // 打开文件选择对话框，使用绝对路径作为默认目录
        const filePath = await open({
            defaultPath: defaultDirPath,
            title: '选择用户数据文件',
            multiple: false,
            filters: [
                { name: 'JSON Files', extensions: ['json'] },
            ]
        });
        // 如果用户选择了文件路径
        if (filePath) {
            // 这里可以调用加载文件的逻辑
            const resFile = new ResFileInfo();
            resFile.filename = filePath.split(/[/\\]/).pop() || '';
            resFile.path = filePath;
            await tryLoadCustomFile(resFile);
        }
    } catch (e) {
        console.error('打开文件对话框错误:', e);
    }
}

async function handleSaveAsFile(): Promise<boolean> {
    try {
        // 获取可执行文件根目录的绝对路径
        const res = await resourceDir();
        console.log("resourceDir", res);
        // 构建完整的默认路径
        const defaultDirPath = `${res}/data/custom`;
        // 打开文件保存对话框，使用绝对路径作为默认目录
        const filePath = await save({
            defaultPath: defaultDirPath,
            title: '保存用户数据文件',
            filters: [
                { name: 'JSON Files', extensions: ['json'] }
            ]
        });

        // 如果用户选择了文件路径
        if (filePath) {
            return await saveCustomAs(filePath);
        }
        return false;
    } catch (e) {
        console.error('保存文件对话框错误:', e);
        return false;
    }

}

//应用用户修改数据到实际mod文件，我们这里要求保存后再应用
async function handleApplyCustomFileToMod() {
    if (hasUnsavedChange()) {
        console.log("applyCustomFileToMod", "有未保存的更改");
        alert("请先保存修改");
        return;
    }
    //获得一份allItems的深拷贝
    const templeD2ItemString: D2ItemString[] = JSON.parse(currentResource.value?.files?.template?.content || '{}');
    for (const item of templeD2ItemString) {
        //检测是否有文字更改
        if (workSpaceModifiedItems?.value?.modifiedItemStrings?.[item.Key]) {
            item.zhCN = workSpaceModifiedItems.value.modifiedItemStrings[item.Key].zhCN || item.zhCN;
            item.zhTW = workSpaceModifiedItems.value.modifiedItemStrings[item.Key].zhTW || item.zhTW;
            item.enUS = workSpaceModifiedItems.value.modifiedItemStrings[item.Key].enUS || item.enUS;
        }
        //检测是否有屏蔽勾选
        if (workSpaceModifiedItems?.value?.ignoreItemKeys?.includes(item.Key)) {
            (item as any)[userLang.value as keyof D2ItemString] = '';
        }

    }
    const modFile = currentResource.value?.files?.mod;
    if (!modFile) {
        console.log("applyCustomFileToMod", "没有mod文件");
        alert("请先加载mod文件");
        return;
    }
    modFile.content = JSON.stringify(templeD2ItemString, null, 2);
    await modFile?.write();
    alert("成功应用修改到mod文件:" + modFile?.path);
    return;
}

async function handelRestoreMod() {
    if (!await confirm("确认要恢复原始mod文件吗？")) {
        return;
    }
    const templateFile = currentResource.value?.files?.template;
    if (!templateFile?.content || !templateFile.content.trim()) {
        await templateFile?.read();
    }
    const modFile = currentResource.value?.files?.mod;
    if (!modFile) {
        console.log("restoreMod", "没有mod文件");
        alert("请先加载mod文件");
        return;
    }
    modFile.content = templateFile?.content;
    await modFile?.write();
    if (currentResource.value?.files) {
        currentResource.value.files.custom = undefined;
    }
    loadCompleteItemStrings(currentResource.value?.name || '', currentResource.value?.files?.template?.content || '{}');
    return;

}






/**如果用户选择了某个语言，那么只有该语言有内容的物品才会算作在地面显示 */
function checkItemIsShowByLang(item: D2ItemString): boolean {
    const validLanguages: Array<keyof D2ItemString> = ['zhCN', 'zhTW', 'enUS'];
    if (validLanguages.includes(userLang.value as keyof D2ItemString)) {
        return item[userLang.value as keyof D2ItemString] !== '';
    }
    return false;
}




// 处理属性面板保存物品事件
const handlePropPanelSaveItem = (item: D2ItemStringToDisplay) => {
    // 查找并更新主物品字符串数组中的对应项
    const index = editItems.value.findIndex(i => i.Key === item.Key);
    if (index !== -1) {
        // 标记为有未保存更改
        hasItemPropChange.value = true;
        if (!workSpaceModifiedItems.value) {
            return;
        }
        // 初始化modifiedItemStrings对象
        workSpaceModifiedItems.value.modifiedItemStrings = workSpaceModifiedItems.value.modifiedItemStrings || {};

        // 查找原始数据中的对应项进行比对
        const originalItem = allItems.value.find(i => i.Key === item.Key);

        // 创建或更新targetModified对象
        const targetModified: any = {};

        // 设置Key值
        targetModified.Key = item.Key;

        // 比对zhCN字段，如果有变化则记录，否则设为undefined
        if (originalItem && item.zhCN !== originalItem.zhCN) {
            targetModified.zhCN = item.zhCN;
        } else {
            targetModified.zhCN = undefined;
        }

        // 比对zhTW字段，如果有变化则记录，否则设为undefined
        if (originalItem && item.zhTW !== originalItem.zhTW) {
            targetModified.zhTW = item.zhTW;
        } else {
            targetModified.zhTW = undefined;
        }

        // 比对enUS字段，如果有变化则记录，否则设为undefined
        if (originalItem && item.enUS !== originalItem.enUS) {
            targetModified.enUS = item.enUS;
        } else {
            targetModified.enUS = undefined;
        }

        if (targetModified.zhCN || targetModified.zhTW || targetModified.enUS) {
            // 有变化，记录到modifiedItemStrings中
            workSpaceModifiedItems.value.modifiedItemStrings[item.Key] = targetModified;
        } else {
            // 无变化，从modifiedItemStrings中删除
            delete workSpaceModifiedItems.value.modifiedItemStrings[item.Key];
        }

        // 更新editItems中的值
        //editItems.value[index] = { ...editItems.value[index], ...item };
    }
};

// 切换属性面板显示/隐藏
const togglePropPanel = () => {
    showPropPanel.value = !showPropPanel.value;
};

// 处理从ItemPropPanel组件发出的装备级别搜索事件
const handleSearchSpecLevelItem = (data: { imageName: string; level: number; originalItemDesc?: any }) => {
    //console.log('接收到装备级别搜索事件:', data);
    displayItems.value = editItems.value.filter(item => item.desc?.imageName === data.imageName && item.desc?.level === data.level);
    // 尝试选中搜索结果中的第一个匹配项
    if (displayItems.value.length > 0) {
        selectedItem.value = displayItems.value[0];
    }
};


const closeItemStringPanel = async () => {
    if (hasUnsavedChange()) {
        // 提示用户保存或放弃更改
        if (await confirm(`${currentResource.value?.name} 有更改，是否保存？`)) {
            //这里调用保存方法
            saveCustom();
        }
        // 重置选中项
        selectedItem.value = undefined;
        currentResource.value = undefined;
    }
}

// 暴露方法给父组件

defineExpose({
    closeItemStringPanel,
});

</script>

<style scoped>
@import "tailwindcss";
</style>